local ngx            = ngx
local log            = require("modules.commhm.log");
local uu             = require("modules.commhm.utils");
local network        = require("modules.commhm.network");

local welfare_config = require('modules.business_welfare.welfare_config')

local FOO = {
    _VERSION       = '0.12.1',
}


local get_gm_cost_svr_url = function ( uin )

    if not welfare_config.gm_cost_server_url then
        return nil
    end

    local server_count  = #welfare_config.gm_cost_server_url
    local http_index    = (uin % server_count) + 1

    return welfare_config.gm_cost_server_url[http_index]
end


local http_get_req = function ( url_, params_ )

	local url_str_ = "";
	for k, v in pairs(params_) do
		url_str_ = url_str_ .. k .. '=' .. ngx.escape_uri(v) .. '&';
	end

	local md5_seed_ = uu.getStringBySortKey( params_ ) .. '522e6ccde68f4584a3282ce0b0eca1cf';
	log.debug( "md5_seed_=" .. md5_seed_ );
	local url_all_ = url_ .. '?' .. url_str_ .. 'sign=' .. ngx.md5( md5_seed_ );
	log.debug( "url_all_=" .. url_all_ );
	local ret, body = network.getHttpPage( url_all_ );
	log.debug( body );

	if  ret == 200 then
		return uu.json2table( body );
	else
		return {};
	end
end


local http_request = function(uin, request, caller)

    local http_url_ = get_gm_cost_svr_url(uin)
    if not http_url_ then
        log.day_list("welfare_cost", "get_gm_cost_svr_url fail")
        return nil
    end

    log.debug( "welfare_cost http GET url=" .. http_url_ );

    uu.var_dump( request );
    local ret_ = http_get_req(http_url_, request);
    uu.var_dump( ret_ );

    if not ret_.return_code or ret_.return_code ~= 'SUCCESS' then

        log.debug( caller .. ' fail');
        log.day_list("welfare_cost",
                     "gm_cost_request",
                     "error",
                     uin,
                     uu.to_str(ret_),
                     uu.to_str(request));
        return nil;
    end

    log.debug( caller .. ' success');
    return ret_;
end


--! @brief 扣除物品
FOO.item_remove = function (itemid, num, reason, exdata)

    local uin_    = ngx.ctx.m_params.uin
    local itemid_ = tonumber(itemid)
    local num_    = tonumber(num)
    local reason_ = tostring(reason) or "welfare_exchange"
    local ext = exdata

    if type(exdata) =="table" then
        ext = uu.table2json(exdata)
    end

    if not itemid_ or itemid_ == 0 or not num_ or num_ == 0 then
        log.day_list("welfare_cost", "item_remove", "id or num is nil", uin_, reason_, uu.to_str({id=itemid_, num=num_}))
    end

    local req_ = {
        cmd    = "item_rm",
        id     = itemid_,
        num    = num_ < 0 and 0 - num_ or num_,
        uin    = uin_,
        ts     = uu.now(),
        reason = reason_,
        ext = ext,
    }

    local ret_ = http_request(uin_, req_, "item_remove")
    if not ret_ then
        log.day_list( "welfare_cost", "item_remove_fail", uu.to_str(req_), uu.to_str(ret_) )
        return false
    end

    log.day_list( "welfare_cost", "item_remove_ok", uu.to_str(req_), uu.to_str(ret_) );
    return true
end


--! @brief 新增物品
--! @param items: {{id=xx,num=xx},{id=xx,num=xx},...}
FOO.items_add = function (items, reason)

    local items_  = {}
    local uin_    = ngx.ctx.m_params.uin
    local reason_ = reason or 'welfare_exchange'

    for _, item in pairs(items) do

        local id  = tonumber(item.id)
        local num = tonumber(item.num)

        if id and id > 0 and num and num > 0 then
            items_[#items_+1] = {id=id, num=num}
        else
            log.day_list('welfare_cost', "items_add", "id or num is nil", uin_, reason_, uu.to_str(item))
        end
    end

    if not next(items_) then
        log.day_list('welfare_cost', "items_add", "items is nil", uin_, reason_, uu.to_str(items))
    end

    local req_   = {
        cmd      ='items_add',
        items    = uu.table2json(items_),
        reason   = reason_,
        uin      = uin_,
        ts       = uu.now(),
    }

    local ret_ = http_request(uin_, req_, "items_add")
    if not ret_ then
        log.day_list( "welfare_cost", "items_add_fail", uu.to_str(req_), uu.to_str(ret_) )
        return false
    end

    log.day_list( "welfare_cost", "items_add_ok", uu.to_str(req_), uu.to_str(ret_) );
    return true
end

--! @brief 修改迷你币
FOO.minicoin_cost = function( uin_, num_, reason_ )

    reason_ = reason_ or "";
    log.debug( "call minicoin_cost, cc=" .. num_ .. ", " .. reason_ );

    if  num_ >= 0 then
        return true
    end

    --扣费
    local req_ = {
        cmd      = "minicoin_rm",       --减迷你币
        minicoin = num_ < 0 and 0 - num_ or num_,
        uin      = uin_,
        ts       = uu.now(),
        reason   = reason_,
    };

    log.day_list( "welfare_cost", "minicoin_begin", uin_, num_, reason_);

    local ret_ = http_request(uin_, req_, "minicoin_cost")
    if not ret_ then

        log.day_list( "welfare_cost", "minicoin_fail", uin_, num_, reason_,uu.to_str(ret_));
        return false
    end

    log.day_list( "welfare_cost", "minicoin_ok", uin_, num_, reason_,uu.to_str(ret_) );

    local rm_from_money = 0

    if        ret_.return_result
    and  type(ret_.return_result) == 'table'
    and  type(ret_.return_result.rm_from_money) == 'boolean' then

        rm_from_money = ret_.return_result.rm_from_money and 1 or 0
    end

    return true, rm_from_money;
end

--修改迷你豆
FOO.minibean_cost = function( uin_, num_, reason_ )

    reason_ = reason_ or "";
    log.debug( "call minibean_cost, cc=" .. num_ .. ", " .. reason_ );

    if  num_ >= 0 then
        return true
    end

    --扣费
    local req_ = {
        cmd      = "minibean_rm",       --减迷你豆
        minibean = num_ < 0 and 0 - num_ or num_,
        uin      = uin_,
        ts       = uu.now(),
        reason   = reason_,
    };

    log.day_list( "welfare_cost", "minibean_begin", uin_, num_, reason_);

    local ret_ = http_request(uin_, req_, "minibean_cost")
    if not ret_ then
        log.day_list( "welfare_cost", "minibean_fail", uin_, num_, reason_, uu.to_str(ret_) );
        return false;
    end

    log.day_list( "welfare_cost", "minibean_ok", uin_, num_, reason_, uu.to_str(ret_) );
    return true, num_;
end

--修改迷你点
FOO.minidian_cost = function( uin_, num_, reason_ )

    reason_ = reason_ or "";
    log.debug( "call minidian_cost, cc=" .. num_ .. ", " .. reason_ );

    if  num_ >= 0 then
        return true
    end

    --扣费
    local req_ = {
        cmd      = "adpoint_rm",        --减迷你点
        num 	 = num_ < 0 and 0 - num_ or num_,
        uin      = uin_,
        ts       = uu.now(),
        reason   = reason_,
    };

    log.day_list( "welfare_cost", "minidian_begin", uin_, num_, reason_ );

    local ret_ = http_request(uin_, req_, "minidian_cost")
    if not ret_ then
        log.day_list( "welfare_cost", "minidian_fail", uin_, num_, reason_, uu.to_str(ret_) );
        return false;
    end

    log.day_list( "welfare_cost", "minidian_ok", uin_, num_, reason_, uu.to_str(ret_) );
    return true, 1;
end

--修改迷你道具
FOO.miniitem_cost = function( uin_, itemid_, num_, reason_ )

    reason_ = reason_ or "";
    log.debug( "call private_change_miniitem, cc=" .. num_ .. ", " .. reason_ );

    if  num_ >= 0 then
        return true
    end

    --扣费
    local req_ = {
        cmd      = "item_rm",
        id       = itemid_,
        num 	 = num_ < 0 and 0 - num_ or num_,
        uin      = uin_,
        ts       = uu.now(),
        reason   = reason_,
    };

    log.day_list( "welfare_cost", "miniitem_begin", uin_, num_, reason_ );

    local ret_ = http_request(uin_, req_, "miniitem_cost")
    if not ret_ then
        log.day_list( "welfare_cost", "miniitem_fail", uin_, num_, reason_, uu.to_str(ret_) );
        return false;
    end

    log.day_list( "welfare_cost", "miniitem_ok", uin_, num_, reason_, uu.to_str(ret_) );
    return true,1;
end

return FOO